'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 一键申请好友
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var Code = require('../../../../consts/code');
var PlayerManager = require('../../../../libs/playerManager');
var friendModel = require('../../../../models/friendModel');
var _ = require('lodash');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var role_id_list = msg.role_id_list;
    if (!role_id_list) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    // 是否好友就是本人
    for (var i = 0; i < role_id_list.length; i++) {
        var friend_role_id = role_id_list[i];
        if (friend_role_id == role_id) {
            return next(null, {
                code: Code.FRIEND_NOT_SELF
            });
        }
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['role', 'friend', 'accrued'], cb);
            },
            function (cb) {
                var friend_model = player_manager.friend;
                _.each(role_id_list, function (role_id) {
                    friend_model.addFriendRecommendList(role_id);
                });

                player_manager.save(cb);
            },
            function (cb) {
                async.each(role_id_list, function (role_item, cb) {
                    _addToFriendRequestList(role_item, role_id, next, cb);
                }, function (err) {
                    if (!!err) {
                        console.error(err);
                        return cb();
                    }
                    cb();
                });
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};

// 把自己ID加入推荐好友申请列表
var _addToFriendRequestList = function (friend_id, role_id, next, cb) {
    var player_manager = new PlayerManager(friend_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.getModel(['role', 'friend', 'accrued'], cb);
            },
            function (cb) {
                var friend_model = player_manager.friend;
                friend_model.addRequest(role_id);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK
            });
        }
    );
};
